package com.hjyoj.judge.strategy;

import cn.hutool.json.JSONUtil;
import com.hjyoj.model.dto.question.JudgeCase;
import com.hjyoj.model.dto.question.JudgeConfig;
import com.hjyoj.judge.codesandbox.model.JudgeInfo;
import com.hjyoj.model.entity.Question;
import com.hjyoj.model.enums.JudgeInfoMessageEnum;

import java.util.List;
import java.util.Optional;

/**
 * java的判题策略
 */
public class JavaJudgeStrategy implements JudgeStrategy {
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        //获取实际所需要的判题时间和判题内存
        Long memory = Optional.ofNullable(judgeInfo.getMemory()).orElse(100L);
        Long time = Optional.ofNullable(judgeInfo.getTime()).orElse(0L);
        List<String> outputlist = judgeContext.getOutputList();
        List<String> inputlist = judgeContext.getInputList();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        Question question = judgeContext.getQuestion();
        //获取题目所需要的时间限制和所需要的内存限制。
        String judgeConfigStr = question.getJudgeConfig();
        JudgeConfig judgeConfigList = JSONUtil.toBean(judgeConfigStr, JudgeConfig.class);
        Long needTimeLimit = judgeConfigList.getTimeLimit();
        Long needMemoryLimit = judgeConfigList.getMemoryLimit();
        JudgeInfo judgeInfoResponse = new JudgeInfo();
        //新增
        judgeInfoResponse.setMemory(memory);
        judgeInfoResponse.setTime(time);
        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.WAITING;
        JudgeInfoMessageEnum judgeInfoMessageEnumAC = JudgeInfoMessageEnum.ACCEPTED;
        //5.1先判断沙箱的执行结果输出数量是否和预期输出数量相等
        if (outputlist.size() != inputlist.size()) {
            judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        //5.2以此判断每一项输出和预期输出是否相等
        for (int i = 0; i < judgeCaseList.size(); i++) {
            JudgeCase judgeCase = judgeCaseList.get(i);
            if (!judgeCase.getOutput().equals(outputlist.get(i))) {
                judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
                judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
                return judgeInfoResponse;
            }
        }
        //5.3判题题目的限制是否符合要求 todo
        if (time - 10L > needTimeLimit) {
            judgeInfoMessageEnum = JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        if (memory > needMemoryLimit) {
            judgeInfoMessageEnum = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
            judgeInfoResponse.setMessage(judgeInfoMessageEnum.getValue());
            return judgeInfoResponse;
        }
        judgeInfoResponse.setMessage(judgeInfoMessageEnumAC.getValue());
        return judgeInfoResponse;
    }
}